"""
图片下载工具模块
支持HTTP和火山引擎TOS多种下载方式
"""
import requests
from PIL import Image
from io import BytesIO
from config import Config

# 导入火山引擎TOS库（可选）
try:
    import tos
    TOS_AVAILABLE = True
except ImportError:
    TOS_AVAILABLE = False


def download_image_from_url(image_url, max_retries=3, timeout=15):
    """
    从URL下载图片，支持多种下载方式
    
    Args:
        image_url: 图片URL
        max_retries: 最大重试次数
        timeout: 超时时间
    
    Returns:
        PIL.Image: 下载的图片对象
        
    Raises:
        Exception: 下载失败时抛出异常
    """
    
    httpUrl = "https://dcp-upload-pro.tos-accelerate.volces.com/" + image_url
    # 检查是否为TOS链接
    if 'tos-cn-' in image_url or 'ivolces.com' in image_url or '2025' in image_url:
        # print('\n🛑 TOS -download ')
        return download_image_from_tos(image_url, max_retries)
    else:
        # print('\n🛑 HTTP -download ')
        return download_image_from_http(httpUrl, max_retries, timeout)


def download_image_from_http(image_url, max_retries=3, timeout=15):
    """使用HTTP请求下载图片"""
    for attempt in range(max_retries):
        try:
            response = requests.get(image_url, timeout=timeout)
            response.raise_for_status()
            image = Image.open(BytesIO(response.content)).convert('RGB')
            return image
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise e
            continue


def download_image_from_tos(image_url, max_retries=3):
    # 从环境变量获取 AK 和 SK 信息。
    # ak = os.getenv('TOS_ACCESS_KEY')
    # sk = os.getenv('TOS_SECRET_KEY')
    ak = "AKLTY2FmZmI5Y2JhYmZmNDc3MmJmOTU3Yjg5Mzk5Y2U2YWM"
    sk = "WVRVMVpEVmtOV1V6TWpRME5HWmxZVGxoTURCbU9HSXpNemRtTURNd1lUUQ=="
    
    # your endpoint 和 your region 填写Bucket 所在区域对应的Endpoint。# 以华北2(北京)为例，your endpoint 填写 tos-cn-beijing.volces.com，your region 填写 cn-beijing。
    endpoint = "tos-cn-guangzhou.ivolces.com"
    region = "cn-guangzhou"
    bucket_name = "dcp-upload-pro"
    # 对象名称，例如 example_dir 下的 example_object.txt 文件，则填写为 example_dir/example_object.txt
    # object_key = "tos://dcp-upload-pro/2025-03-22/01e00bdc-d0c6-4db5-b4a0-caae297e6fa5.jpg"
    # object_key = "2025-03-04/8da937a0-9777-4e9e-ad3d-749af08a34cb.jpg"
    
    try:
        # 创建 TosClientV2 对象，对桶和对象的操作都通过 TosClientV2 实现
        client = tos.TosClientV2(ak, sk, endpoint, region)
        # 若 file_name 为目录则将对象下载到此目录下, 文件名为对象名
        file_name = '/data/temp/images/' + image_url.split('/', 1)[-1] if '/' in image_url else image_url
        filedown = client.get_object_to_file(bucket_name, image_url, file_name)
        # print(f'下载URL,STEP 1:{image_url}')
        # print(f'图片下载到,STEP 2:{file_name}')

        return Image.open(file_name).convert('RGB')

    except tos.exceptions.TosClientError as e:
        # 操作失败，捕获客户端异常，一般情况为非法请求参数或网络异常
        print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause))
    except tos.exceptions.TosServerError as e:
        # 操作失败，捕获服务端异常，可从返回信息中获取详细错误信息
        print('fail with server error, code: {}'.format(e.code))
        # request id 可定位具体问题，强烈建议日志中保存
        print('error with request id: {}'.format(e.request_id))
        print('error with message: {}'.format(e.message))
        print('error with http code: {}'.format(e.status_code))
        print('error with ec: {}'.format(e.ec))
        print('error with request url: {}'.format(e.request_url))
    except Exception as e:
        print('fail with unknown error: {}'.format(e))
    except Exception as e:
        print('fail with unknown error: {}'.format(e))


def _parse_tos_url(image_url):
    """
    解析TOS URL，返回bucket、object_key、region、endpoint
    支持: tos://bucket/object_key 或 https://tos-cn-region.ivolces.com/bucket/object_key
    """
    bucket_name = ""
    object_key = ""
    region = 'cn-guangzhou'
    endpoint = 'tos-cn-guangzhou.ivolces.com'
    
    if image_url.startswith('tos://'):
        # tos://dcp-upload-pro/2025-03-22/filename.jpg
        url_parts = image_url.replace('tos://', '').split('/', 1)
        bucket_name = url_parts[0]
        object_key = url_parts[1] if len(url_parts) > 1 else ''
        
    elif 'ivolces.com' in image_url:
        # https://tos-cn-guangzhou.ivolces.com/bucket/object_key
        from urllib.parse import urlparse
        parsed = urlparse(image_url)
        path_parts = parsed.path.lstrip('/').split('/', 1)
        bucket_name = path_parts[0] if path_parts else ''
        object_key = path_parts[1] if len(path_parts) > 1 else ''
        
        # 从主机名推断region
        if 'tos-cn-guangzhou' in parsed.hostname:
            region = 'cn-guangzhou'
            endpoint = 'tos-cn-guangzhou.ivolces.com'
        elif 'tos-cn-beijing' in parsed.hostname:
            region = 'cn-beijing'
            endpoint = 'tos-cn-beijing.ivolces.com'
        else:
            # 默认使用广州区域
            region = 'cn-guangzhou'
            endpoint = 'tos-cn-guangzhou.ivolces.com'
    
    return bucket_name, object_key, region, endpoint
